package servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

public class FileUploadServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        //1.判断是不是文件表单(enctype="multipart/form-data")
        if(ServletFileUpload.isMultipartContent(req)) {
            //2.创建DiskFileItemFactory对象，用于构建一个解析上传数据的工具对象
            DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
            //3.创建一个用于解析上传数据的工具对象
            /*
                表单提交的数据就是 input元素

                家居图: <img src="img/8.jpg" alt="" width="200" height="200" id="prevView"><br/>
                <input type="file" name="pic" id="" value="" onchange="prev(this)"/><br/>
                家居名: <input type="text" name="name"><br/>
             */
            ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);
            //解决接收到的文件名是中文乱码的问题
            servletFileUpload.setHeaderEncoding("UTF-8");
            //4.servletFileUpload可以把表单提交的数据(文本、文件)
            //  将其封装到 FileItem 文件项中
            /*
                list[name=mysql.png, StoreLocation=D:\Tomcat\apache-tomcat-9.0.85-windows-x64\apache-tomcat-9.0.85\temp\\upload__3e338333_197da959e0d__7fd7_00000002.tmp, size=232452bytes, isFormField=false, FieldName=pic,
                name=null, StoreLocation=D:\Tomcat\apache-tomcat-9.0.85-windows-x64\apache-tomcat-9.0.85\temp\\upload__3e338333_197da959e0d__7fd7_00000003.tmp, size=1bytes, isFormField=true, FieldName=name]
             */
            try {
                List<FileItem> list = servletFileUpload.parseRequest(req);
                //遍历并分别处理
                for (FileItem fileItem : list) {
                    //判断是不是一个文件
                    if (fileItem.isFormField()) {   //如果为真，就是文本
                        String name = fileItem.getString("utf-8");
                        System.out.println("家具名：" + name);
                    } else {    //是文件
                        String name = fileItem.getName();
                        System.out.println("上传的文件名：" + name);

                        //把上传到服务器的temp目录下的文件保存到指定的目录
                        //1.指定一个保存的目录，就是我们网站工作目录下
                        String filePath = "/upload/";
                        //2.获取到完整目录
                        String realPath =
                                req.getServletContext().getRealPath(filePath);
                        //3.创建上传的目录
                        File fileRealPathDirectory = new File(realPath + WebUtils.getYearMonthDay());
                        //工具类，可以返回 /2025/07/05 日期的目录路径
                        if (!fileRealPathDirectory.exists()) {
                            //不存在就创建目录
                            fileRealPathDirectory.mkdirs();
                        }
                        //4.将temp目录下的临时文件拷贝到真正目录下
                        //  对上传的文件名进行处理，前面增加一个前缀，保证是唯一即可，防止上传时文件名和服务端一致导致文件被替换
                        name = UUID.randomUUID() + "_" + name;
                        String fileFullPath = fileRealPathDirectory + "/" + name;
                        fileItem.write(new File(fileFullPath));
                        //5.提示信息
                        resp.setContentType("text/html;charset=utf-8");
                        resp.getWriter().write("上传成功");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("不是文件表单");
        }
    }
}
